package com.yiwei.jmx.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.jmx.R;
import com.yiwei.jmx.activity.V3XueXinForgetpassActivity;
import com.yiwei.jmx.activity.V3XueXinIdentityActivity;
import com.yiwei.jmx.activity.V3XueXinRegisterActivity;
import com.yiwei.jmx.activity.XueXinQuestionActivity;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.ChsiBean;
import com.yiwei.jmx.api.bean.ChsiLoginBean;
import com.yiwei.jmx.event.FindXueXinUsernameEvent;
import com.yiwei.jmx.util.ImageUtil;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.Spans;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-7-10.
 */

public class V3XueXinLoginFragment extends BaseFragment {


    @BindView(R.id.edit_account)
    EditText editAccount;
    @BindView(R.id.btn_account_delete)
    ImageView btnAccountDelete;
    @BindView(R.id.edit_pass)
    EditText editPass;
    @BindView(R.id.btn_pass_delete)
    ImageView btnPassDelete;
    @BindView(R.id.btn_pass_eye)
    ImageView btnPassEye;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.code_view)
    LinearLayout codeView;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.img_icon_center)
    ImageView imgIconCenter;
    @BindView(R.id.btn_check)
    ImageView btnCheck;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.btn_forget)
    TextView btnForget;
    @BindView(R.id.btn_register)
    TextView btnRegister;
    @BindView(R.id.btn_question)
    TextView btnQuestion;
    private Unbinder unbinder;
    private boolean isCheck = true;
    private boolean isChecked = false;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_xuexin_login_v3;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
//        Spanned txt_agree = Spans.with(this).font("我已同意并阅读", getResources().getDimensionPixelSize(R.dimen.x24), 0xffBBC7D6).font("《智信管家服务协议》", getResources().getDimensionPixelSize(R.dimen.x24), 0xff0072FF).build();
//        txtAgree.setText(txt_agree);
        UI.setTvHtml(txtAgree, R.string.txt_agree);
    }

    @OnTextChanged({R.id.edit_account, R.id.edit_pass})
    void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(UI.toString(editAccount)) && !TextUtils.isEmpty(UI.toString(editPass))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    public void getChsiCode(String username, String password) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }

        ChsiBean bean = new ChsiBean();
        bean.username = username;
        bean.password = password;
        Api.api_service.getChsiCodeInfo(bean).compose(RxLifeUtil.checkOn(getContext())).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(model -> {
                    String imgStr = "";
                    if (model.data.contains(",")) {
                        imgStr = model.data.substring(model.data.indexOf(',') + 1);
                        imgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
                        codeView.setVisibility(View.VISIBLE);
                    } else imgCode.setImageDrawable(null);
                });
    }

    public void getChsiLogin(String username, String password, String captcha) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }
        ((V3XueXinIdentityActivity) getActivity()).loadingDialog.show();
        ChsiLoginBean bean = new ChsiLoginBean();
        bean.username = username;
        bean.password = password;
        if (!TextUtils.isEmpty(captcha)) {
            bean.captcha = captcha;
        }
//
        Api.api_service.getChsiLoginInfo(bean).compose(RxLifeUtil.NocheckOn(getContext())).
                doFinally(() -> {
                    try {
                        ((V3XueXinIdentityActivity) getActivity()).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1) {
                        ToastUtil.makeText(getContext(), "认证成功").show();
                        getActivity().finish();
                    } else if (result.getStatus() == 2) {
                        if (codeView.getVisibility() == View.VISIBLE) {
                            ToastUtil.makeText(getContext(), "图片验证码错误");
                        }
                        codeView.setVisibility(View.VISIBLE);
                        String imgStr = "";
                        String code = result.captchaImage;
                        if (code.contains(",")) {
                            imgStr = code.substring(code.indexOf(',') + 1);
                            imgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
                        } else imgCode.setImageDrawable(null);
                    } else {
                        ToastUtil.makeText(getContext(), result.getMsg()).show();
                        getChsiCode(UI.toString(editAccount), UI.toString(editPass));
                    }
                });
    }

    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FindXueXinUsernameEvent msg) {
//        editAccount.setText(UserGlobal.getFindXueXinUsername());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }


    public boolean checkUsername() {
        if (TextUtils.isEmpty(UI.toString(editAccount))) {
            ToastUtil.makeText(getContext(), "学信网账号不能为空").show();
            return false;
        }
        return true;
    }

    public boolean checkPassword() {
        if (TextUtils.isEmpty(UI.toString(editPass))) {
            ToastUtil.makeText(getContext(), "学信网密码不能为空").show();
            return false;
        }
        return true;
    }

    @OnClick({R.id.img_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.img_code:
                if (checkUsername() && checkPassword())
                    getChsiCode(UI.toString(editAccount), UI.toString(editPass));
                break;
//            case R.id.btn_register:
//                Util.startActivity(getContext(), V3XueXinRegisterActivity.class);
//                break;


            case R.id.btn_submit:
                if (checkUsername() && checkPassword())
                    getChsiLogin(UI.toString(editAccount), UI.toString(editPass), UI.toString(editCode));
                break;

        }
    }

    @OnClick({R.id.btn_check, R.id.txt_agree, R.id.btn_forget, R.id.btn_register, R.id.btn_question})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.btn_check:
                isCheck = !isCheck;
                if (isCheck) {
                    btnCheck.setImageResource(R.mipmap.img_step_check);
                } else {
                    btnCheck.setImageResource(R.mipmap.img_step_uncheck);
                }
                break;
            case R.id.txt_agree:
                break;
            case R.id.btn_forget:
                Util.startActivity(getContext(), V3XueXinForgetpassActivity.class);
                break;
            case R.id.btn_register:
                Util.startActivity(getContext(), V3XueXinRegisterActivity.class);
                break;
            case R.id.btn_question:
                Util.startActivity(getContext(), XueXinQuestionActivity.class);
                break;
        }
    }

    @OnClick({R.id.btn_account_delete, R.id.btn_pass_delete, R.id.btn_pass_eye})
    public void onViewClicked2(View view) {
        switch (view.getId()) {
            case R.id.btn_account_delete:
                editAccount.setText("");
                break;
            case R.id.btn_pass_delete:
                editPass.setText("");
                break;
            case R.id.btn_pass_eye:
                isChecked = !isChecked;
                if (isChecked) {
                    //如果选中，显示密码
                    editPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    btnPassEye.setImageResource(R.mipmap.img_eye_open);
                } else {
                    //否则隐藏密码
                    editPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    btnPassEye.setImageResource(R.mipmap.img_eye_close);
                }
                break;
        }
    }
}
